package com.lyf.scm.admin.domain.util;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DownLoadUtil {
    private static final Pattern P = Pattern.compile("\\s*|\t|\r|\n");
    /**
     * 下载文件
     */
    public static void download(HttpServletResponse response, String fileName, byte[] data) throws Exception {
        if (fileName == null) {
            fileName = "";
        }
        fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
        if (data != null) {
            response.setContentLength(data.length);
        }
        Matcher m = P.matcher(fileName);
        fileName = m.replaceAll("");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.setContentType("application/octet-stream");
        if (data != null) {
            response.getOutputStream().write(data);
        }
    }

    public static void download(HttpServletResponse response, File file) throws Exception {
        download(response, file.getName(), getBytesFromFile(file));
    }
    /**
     * 将文件对象转换为byte[]数组
     *
     * @param f
     * @return
     */
    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        FileInputStream stream = null;
        ByteArrayOutputStream out = null;
        try {
            stream = new FileInputStream(f);
            out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1) {
                out.write(b, 0, n);
            }
            return out.toByteArray();
        } catch (IOException e) {
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
            }
        }
        return null;
    }
}